package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Appointment;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.entityVo.AppointmentVo;
import com.antdesignbackend.backend.entity.entityVo.RoomVo;
import com.antdesignbackend.backend.entity.Room;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/appointment")
public class AppointmentController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    private Integer menuId;
    private Integer userId;
    private Integer userType;
    private String roleID;
    @Autowired
    private IShopService shopService;
    @Autowired
    UserController userController;
    @Autowired
    private IRoomService roomService;
    @Autowired
    IAppointmentService appointmentService;
    /**
     * 线下预约
     */
    @GetMapping("/index")
    @AuthToken
    public String index(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "appointment/index";
    }
    /**
     * 人工预约
     */
    @GetMapping("/personIndex")
    @AuthToken
    public String personIndex(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "appointment/personIndex";
    }
    /**
     * 挂账预约
     */
    @GetMapping("/hangingIndex")
    @AuthToken
    public String hangingIndex(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "appointment/hangingIndex";
    }
    /**
     * 预约记录
     */
    @GetMapping("/listIndex")
    @AuthToken
    public String listIndex(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "appointment/listIndex";
    }
    /**
     * 流水报表
     */
    @GetMapping("/flowIndex")
    @AuthToken
    public String flowIndex(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "flowManagement/flowIndex";
    }
    /**
     * 退款申请
     */
    @GetMapping("/refundIndex")
    @AuthToken
    public String refundIndex(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "flowManagement/refundIndex";
    }

    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody AppointmentVo data,HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<AppointmentVo> datalist=new ArrayList<>();
        QueryWrapper<AppointmentVo> wrapper =new QueryWrapper<AppointmentVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            List<Integer> idList= userController.idList(userId);
            wrapper.in("userID",idList);
        }
        //正常查询过滤条件
        wrapper.ge("t.state",0);
        if(data.getShopId()!=null && !data.getShopId().equals(""))
        {
            wrapper.eq("t2.shopId",data.getShopId());
        }
        if(data.getStartTimeStr()!=null && !data.getStartTimeStr().equals(""))
        {
            wrapper.ge("t.startTime",data.getStartTimeStr());
        }
        if(data.getEndTimeStr()!=null && !data.getEndTimeStr().equals(""))
        {
            wrapper.le("t.endTime",data.getEndTimeStr());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=appointmentService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= appointmentService.search(wrapper.orderByDesc("startTime"),new Page<>(data.getPageIndex(),data.getPageSize()));
            //得到当前菜单具备的功能权限
//            List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//            datalist.forEach(model -> model.setButtonList(list));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 操作相关，通过action 区分
     * @return
     */
    @PostMapping("/action")
    @ResponseBody
    public ReturnVO actions(@RequestBody AppointmentVo vo, HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        String errorMsg="保存失败！";
        switch (vo.getAction()) {

            case "appointment":
                //预约
                //先看是否可以预约
                   Boolean b1=appointmentService.IsAppointment(vo.getRoomId(),vo.getStartTimeStr(),vo.getEndTimeStr());
                if(b1)
                {
                    Boolean dd=appointmentService.AddAppointment(vo);
                    b=true;
                }
                else
                {
                    b=false;
                }

                break;
            case "restDownCard":
                b=true;
                break;
            default:
                break;
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage(errorMsg);
            result.setCode("500");
        }
        return result;
    }
    /***
     * 人工预约
     * @return
     */
    @PostMapping("/peoAction")
    @ResponseBody
    public ReturnVO peoAction(@RequestBody AppointmentVo vo, HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        String errorMsg="保存失败！";
        Boolean b=appointmentService.peoAddAppointment(vo);
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else{
            result.setMessage(errorMsg);
            result.setCode("500");
        }
        return result;
    }
    /***
     * 获取流水报表图表数据
     * @return
     */
    @PostMapping("/getFlowListMap")
    @ResponseBody
    public Map<String, Object> getFlowListMap(@RequestBody AppointmentVo vo) throws Exception {
        Map<String, Object> resultmap= new HashMap<>();
        List<String> typenames=new ArrayList<>();
        List<String> shopnames=new ArrayList<>();
        //先获取收费类目
        List<RoomVo> typeList = new ArrayList<>();
        QueryWrapper<RoomVo> wrapper =new QueryWrapper<>();
        //根据权限生成过滤条件
        if(roleID.equals("1") || roleID.equals("2"))
        {//管理员
        }
        else if(roleID.equals("3"))
        {
            wrapper.inSql("userId","select userid from users where Activity=1 and (UserID="+userId+" or parentID="+userId+")");
        }
        wrapper.eq("state",1);
        try
        {
            //项目类别
            typeList = roomService.search(wrapper.orderByAsc("name"),new Page<>(1,99999));
            if(typeList.size()==0) return resultmap;
            for (Room item1:typeList) {
                typenames.add(item1.getName());
            }
            resultmap.put("typenames",typenames);
            //店铺
            QueryWrapper<Shop> wrappershop =new QueryWrapper<>();
            wrappershop.eq("state",1);
            //根据权限生成过滤条件
            if(roleID.equals("1") || roleID.equals("2"))
            {//管理员
            }
            else if(roleID.equals("3"))
            {
                wrappershop.inSql("userId","select userid from users where Activity=1 and (UserID="+userId+" or parentID="+userId+")");
            }
            if(vo.getShopId()!=null && !vo.getShopId().equals(""))
            {
                wrappershop.eq("id",vo.getShopId());
            }
            wrappershop.eq("merchantType",4);
            List<Shop> shopList = shopService.getBaseMapper().selectList(wrappershop);
            if(shopList.size()==0) return resultmap;
            for (Shop item2:shopList) {
                shopnames.add(item2.getName());
            }
            resultmap.put("shopnames",shopnames);
            QueryWrapper<AppointmentVo> wrapperlist =new QueryWrapper<>();
            //根据权限生成过滤条件
            if(roleID.equals("1") || roleID.equals("2"))
            {//管理员
            }
            else if(roleID.equals("3"))
            {
                wrapperlist.inSql("t3.userId","select userid from users where Activity=1 and (UserID="+userId+" or parentID="+userId+")");
            }
            if(vo.getStartTimeStr()!=null && !vo.getStartTimeStr().equals(""))
            {
                String start=vo.getStartTimeStr();
                wrapperlist.ge("t.startTime",start);
            }
            if(vo.getEndTimeStr()!=null && !vo.getEndTimeStr().equals(""))
            {
                String end=vo.getEndTimeStr();
                wrapperlist.le("t.endTime",end);
            }
            if(vo.getShopId()!=null && !vo.getShopId().equals(""))
            {
                wrapperlist.eq("t2.shopId",vo.getShopId());
            }
            wrapperlist.eq("t.state",1);
            wrapperlist.eq("t3.merchantType",4);
            List<AppointmentVo> datafeelist=appointmentService.search(wrapperlist,new Page<>(1,99999));
            List<Object> series=new ArrayList<>();
            Map<String,Object> valueItem1=new HashMap();
            List<Double> amountList=new ArrayList<>();
            for (Room item1:typeList) {
                boolean flag=false;
                List<AppointmentVo> filterdata=datafeelist.stream().filter(s->s.getRoomId().equals(item1.getId())).collect(Collectors.toList());
                for(AppointmentVo fee:filterdata){
                    if(fee.getRoomName().equals(item1.getName())){
                        flag=true;
                    }
                }
                if(flag==true){
                    valueItem1=new HashMap();
                    amountList=new ArrayList<>();
                    valueItem1.put("name",item1.getName());
                    valueItem1.put("type","bar");
                    for (Shop item2:shopList){
                        List<AppointmentVo> fildata=filterdata.stream().filter(s->s.getShopName().equals(item2.getName())).collect(Collectors.toList());
                        if(fildata.size()>0){
                            amountList.add(fildata.stream().mapToDouble(AppointmentVo::getAmount).sum());
                        }else{
                            amountList.add(0.0);
                        }
                    }
                    valueItem1.put("data",amountList);
                    series.add(valueItem1);
                }
            }
            resultmap.put("series",series);
        }
        catch(Exception ex)
        {
            logger.error(ex.getMessage());
        }
        return resultmap;
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/refundSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO refundSearch(@RequestBody AppointmentVo data,HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<AppointmentVo> datalist=new ArrayList<>();
        QueryWrapper<AppointmentVo> wrapper =new QueryWrapper<AppointmentVo>();
        //正常查询过滤条件
        wrapper.eq("t.state",1);
        wrapper.eq("t.isUse",0);
        wrapper.eq("t.isCancel",1);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=appointmentService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= appointmentService.search(wrapper.orderByDesc("startTime"),new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
}
